from flask import Blueprint, render_template, g, redirect, request, flash, url_for, current_app
from flask_paginate import Pagination

from exts import db
from forms.cms import AddStaffForm, EditStaffForm, EditBoardForm, AddBoardForm
from models.post import PostModel, CommentModel, BoardModel
from models.user import PermissionEnum, UserModel, RoleModel
from decorators import permission_required
from utils import restful

bp = Blueprint('cms', __name__, url_prefix='/cms')


@bp.context_processor
def cms_context_processor():
    return {
        'PermissionEnum': PermissionEnum
    }


@bp.before_request
def cms_before_request():
    if not hasattr(g, 'user') or g.user.is_staff == False:
        return redirect('/')


def pagenate(query_obj,query_obj_name):
    page = request.args.get('page', type=int, default=1)
    start = (page - 1)*current_app.config.get('PER_PAGE_COUNT')
    end = start + current_app.config.get('PER_PAGE_COUNT')
    total = query_obj.count()
    query_obj = query_obj.slice(start, end)
    pagination = Pagination(bs_vesion=4, page=page, total=total, outer_window=0, inner_window=2, alignment='center')
    return {query_obj_name: query_obj, 'pagination': pagination}



@bp.get('')
def index():
    return render_template('cms/index.html')


@bp.get('/staff/list')
@permission_required(PermissionEnum.CMS_USER)
def staff_list():
    users = UserModel.query.filter_by(is_staff=True)
    context = pagenate(users, 'users')
    return render_template('cms/staff_list.html', **context)

@bp.route('/staff/add', methods=['GET', 'POST'])
@permission_required(PermissionEnum.CMS_USER)
def staff_add():
    if request.method == 'GET':
        roles = RoleModel.query.all()
        return render_template('cms/add_staff.html', roles=roles)
    else:
        form = AddStaffForm(request.form)
        if form.validate():
            email = form.email.data
            role_id = form.role.data
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                flash('用户不存在！')
                return redirect(url_for('cms.staff_add'))
            user.is_staff = True
            user.role = RoleModel.query.get(role_id)
            db.session.commit()
            return redirect(url_for('cms.staff_list'))





@bp.route('/staff/edit/<string:user_id>', methods=['GET', 'POST'])
@permission_required(PermissionEnum.CMS_USER)
def staff_edit(user_id):
    edit_user = UserModel.query.get(user_id)
    if request.method == 'GET':
        roles = RoleModel.query.all()
        return render_template('cms/edit_staff.html', edit_user=edit_user, roles=roles)
    else:
        form = EditStaffForm(request.form)
        if form.validate():
            role_id = form.role.data
            print(f'这是前端页面传过来的role_id:{role_id}')
            # is_staff = form.is_staff.data
            is_staff = request.form.get('is_staff')
            print(f'这是前端页面传过来的is_staff:{is_staff}')
            print(f'这是用户对象edit_user的is_staff属性:{edit_user.is_staff}')
            edit_user.is_staff = int(is_staff)
            print(f'这是处理后的用户对象edit_user的is_staff属性:{edit_user.is_staff}')
            if edit_user.role.id != role_id:
                edit_user.role = RoleModel.query.get(role_id)
            db.session.commit()
            return redirect(url_for('cms.staff_edit', user_id=user_id))
        else:
            for message in form.messages:
                flash(message)
            return redirect(url_for('cms.staff_edit', user_id=user_id))


@bp.route('/users')
@permission_required(PermissionEnum.FRONT_USER)
def user_list():
    users = UserModel.query.filter_by(is_staff=False)
    context = pagenate(users, 'users')
    return render_template('cms/users.html', **context)


@bp.post('/users/active/<string:user_id>')
@permission_required(PermissionEnum.FRONT_USER)
def active_user(user_id):
    is_active = request.form.get('is_active', type=int)
    print(f'这是前端页面传过来的is_active:{is_active}')
    print(f'这是前端页面传过来的is_active的类型:{type(is_active)}')
    if is_active == None:
        return restful.params_error(message='请传入is_active参数')
    user_active = UserModel.query.get(user_id)
    print(f'这是用户对象user的is_active属性:{user_active.is_active}')
    user_active.is_active = bool(is_active)
    print(f'这是处理后的用户对象user的is_active属性:{user_active.is_active}')
    db.session.commit()
    return restful.ok()


@bp.get('/posts')
@permission_required(PermissionEnum.POST)
def post_list():
    posts = PostModel.query.order_by(PostModel.create_time.desc())
    context = pagenate(posts, 'posts')
    return render_template('cms/posts.html', **context)


@bp.post('/posts/active/<int:post_id>')
@permission_required(PermissionEnum.POST)
def active_post(post_id):
    is_active = request.form.get('is_active', type=int)
    if is_active == None:
        return restful.params_error(message='请传入is_active参数')
    post_active = PostModel.query.get(post_id)
    post_active.is_active = bool(is_active)
    db.session.commit()
    return restful.ok()


@bp.route('/comments')
def comment_list():
    comments = CommentModel.query.order_by(CommentModel.create_time.desc())
    context = pagenate(comments, 'comments')
    return render_template('cms/comments.html', **context)


@bp.post('/comments/active/<int:comment_id>')
@permission_required(PermissionEnum.COMMENT)
def active_comment(comment_id):
    is_active = request.form.get('is_active', type=int)
    if is_active == None:
        return restful.params_error(message='请传入is_active参数')
    comment = CommentModel.query.get(comment_id)
    comment.is_active = bool(is_active)
    db.session.commit()
    return restful.ok()


@bp.route('/boards')
@permission_required(PermissionEnum.BOARD)
def board_list():
    boards = BoardModel.query.order_by(BoardModel.create_time.desc())
    context = pagenate(boards, 'boards')
    return render_template('cms/boards.html', **context)


@bp.post('/boards/active/<int:board_id>')
@permission_required(PermissionEnum.BOARD)
def active_board(board_id):
    is_active = request.form.get('is_active', type=int)
    if is_active == None:
        return restful.params_error(message='请传入is_active参数')
    board = BoardModel.query.get(board_id)
    board.is_active = bool(is_active)
    db.session.commit()
    return restful.ok()


@bp.route('/board/edit/<string:board_id>', methods=['GET', 'POST'])
@permission_required(PermissionEnum.BOARD)
def board_edit(board_id):
    board = BoardModel.query.get(board_id)
    if request.method == 'GET':
        return render_template('cms/edit_board.html', board=board)
    else:
        form = EditBoardForm(request.form)
        if form.validate():
            name = form.name.data
            print(f'这是前端页面传过来的name:{name}')
            print(f'这是board对象的name属性:{board.name}')
            if board.name != name:
                board.name = name
                db.session.commit()
            return redirect(url_for('cms.board_edit', board_id=board_id))
        else:
            for message in form.messages:
                flash(message)
            return redirect(url_for('cms.board_edit', board_id=board_id))


@bp.route('/board/add', methods=['GET', 'POST'])
@permission_required(PermissionEnum.BOARD)
def board_add():
    if request.method == 'GET':
        return render_template('cms/add_board.html')
    else:
        form = AddBoardForm(request.form)
        if form.validate():
            name = form.name.data
            boards = BoardModel.query.all()
            name_list = [board.name for board in boards]
            print(f'这是boards对象的name_list:{name_list}')
            if name in name_list:
                flash('此板块已经存在')
                return redirect(url_for('cms.board_add'))
            new_board = BoardModel(name=name)
            db.session.add(new_board)
            db.session.commit()
            return redirect(url_for('cms.board_list'))
